//
//  ReaderFileViewController.m
//  Reader
//
//  Created by Kiran Panesar on 15/10/2014.
//
//

#import "ReaderFileViewController.h"
#import "ReaderViewController.h"
#import "UIViewController+WSJLodingView.h"
#import "UIImage+SQExtension.h"

#import "JCDownloader.h"
//#import "JFFileManager.h"
#import "JCAlertView.h"

#import "AppDelegate.h"
#import <UMMobClick/MobClick.h>
#import "HELPDFfileCacheTool.h"
#import "BTCourseModel.h"
#import "CKHttpCommunicate.h"




@interface ReaderFileViewController () <UIAlertViewDelegate>


@property (nonatomic,  strong) JCDownloadOperation *operation;


@property (nonatomic,  assign) NSInteger studiedSeqNum;


@property (nonatomic,  strong) MBProgressHUD *bar;


@property (nonatomic,  strong) NSString *url;


@end

@implementation ReaderFileViewController

#pragma mark ReaderViewControllerDelegate

- (void)dismissReaderViewController:(ReaderViewController *)viewController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor whiteColor];
    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame =CGRectMake(0, 0, 16, 28);
    [btn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
//    [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *back =[[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.navigationItem.leftBarButtonItem = back;
   [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:kMainColor] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
//    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
//    [[UINavigationBar appearance] setTintColor:kMainColor];
    
    
// 没有网络的时候
    /*
    weakSelf_define;
    HELNetworkStatus statues =[BTNetworkManager sharedMg].netStatus;
    if (statues == 0) {
        NSString *filePath =[HELPDFfileCacheTool isChchedWithPdfFilename:self.pdfName];
        if (filePath) {
            
            NSNumber *page =  [HELPDFfileCacheTool getLastPageFromKey:self.pdfName];
            if (page) {
                self.studiedSeqNum =[page integerValue];
            }else{
                self.studiedSeqNum = 1;
            }
            
            [self preparePdfWithFilePath:filePath];
            return ;
        }else{
          
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"当前pdf并未缓存在本地" ButtonType:1 ButtonTitle:@"返回" Click:^{
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            }];
        }
        return;
    }
    
    // 网络正常直接请求进度
    [self getPdfUrl];
     /Users/wangsujin1/BaxTer/BaxTer/003.pdf
     */
   
    //测试代码
//    NSURL *url = [[NSBundle mainBundle] URLForResource:@"003" withExtension:@"pdf"];
//    [self preparePdfWithFilePath:url.path];
    [self downPdfFile];
    
    
}


- (void)backAction{
    
    if ([self.course.courseStatus integerValue] >=2) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    //测试代码
//    [self dismissViewControllerAnimated:YES completion:nil];
    

    UIAlertView *alerView =[[UIAlertView alloc] initWithTitle:@"提示" message:@"是否确认退出并保存进度" delegate:self cancelButtonTitle:@"继续学习" otherButtonTitles:@"退出并保存",nil];
    [alerView show];
   

  
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex ==1) {
        [self uploadLearnProgress];
    }
}

- (void)uploadLearnProgress{

    
 
    weakSelf_define;
    
    [self dismissViewControllerAnimated:YES completion:^{
        if (_readerViewController.isFinished == YES){
            //本地 进度更新 为总页数
            [HELPDFfileCacheTool saveLastPage:[_readerViewController.document numberOfPages] withPdfKey:weakSelf.course.courseName];
            //            alertMessage(@"课程完结,不请求啦~");
            return ;
        }
        
    }];
    
    
    NSMutableDictionary *params =[NSMutableDictionary
                                  dictionary];
    
    params[@"progressPage"] =@(_readerViewController.maxReadPage);
    params[@"courseID"] =@([self.course.id integerValue]);
    [[BTNetworkManager sharedMg] POST:kUpdateLearningProgess parameters:params success:^(NSDictionary *responseObject) {
        
        if (responseObject[@"err"]&& ![responseObject[@"err"] isKindOfClass:[NSNull class]]) {
            alertMessage(responseObject[@"err"]);
        }else{
            
            NSString *str =[NSString stringWithFormat:@"保存成功, 您学习到第%li页",(long)_readerViewController.maxReadPage];
            [HELPDFfileCacheTool saveLastPage:_readerViewController.maxReadPage withPdfKey:weakSelf.course.courseName];
            
            alertMessage(str);
            if (weakSelf.callBack) {
                weakSelf.callBack();
            }
            
        }
        
    } failure:^(NSString *err) {
        [HELPDFfileCacheTool saveLastPage:_readerViewController.maxReadPage withPdfKey:weakSelf.course.courseName];
    }];


/*

//    这里还需要判断下是否已经完成过学习 ,完成过则不需要请求
 
    defineWeakSelf;
    [self dismissViewControllerAnimated:YES completion:^{
        
        if (_readerViewController.isFinished == YES) {
         //本地 进度更新 为总页数
            [HELPDFfileCacheTool saveLastPage:[_readerViewController.document.pageCount integerValue] withPdfKey:weakSelf.pdfName];
//            alertMessage(@"课程完结,不请求啦~");
            return ;
        }
        
        NSMutableDictionary *params =[NSMutableDictionary
                                    dictionary];
        weakSelf_define;
        params[@"userId"] = HEL_USERID;
        params[@"seqNum"] =@(_readerViewController.maxReadPage);
        params[@"tblStudyDataId"] =@(self.courseId);
        [[BTNetworkManager sharedMg] GET:kUploadLearningProgress parameters:params success:^(NSDictionary *responseObject) {
            
            if (responseObject[@"exception"]) {
                alertMessage(responseObject[@"exception"]);
            }else{
                NSString *str =[NSString stringWithFormat:@"保存成功, 您学习到第%li页",(long)_readerViewController.maxReadPage];
                  [HELPDFfileCacheTool saveLastPage:_readerViewController.maxReadPage withPdfKey:weakSelf.pdfName];
                alertMessage(str);
                 [MobClick event:@"StudyCount" label:deviceName];
                if (weakSelf.callBack) {
                    weakSelf.callBack();
                }
                
            }
            
        } failure:^(NSString *err) {
             [HELPDFfileCacheTool saveLastPage:_readerViewController.maxReadPage withPdfKey:weakSelf.pdfName];
        }];
    }];
  */
}



- (void)dealloc{
   
 
    
   
}

- (void)downPdfFile{
   

    NSString *filePath =[HELPDFfileCacheTool isChchedWithPdfFilename:self.course.courseName isMP4:NO];
    if (filePath) {
       
        [self preparePdfWithFilePath:filePath];
        return ;
    };
    weakSelf_define;
   
    __block MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
    hud.animationType = MBProgressHUDAnimationZoomOut;
    hud.detailsLabelText = @"正在下载...";
    hud.progress = 0;
    [hud show:YES];
    self.bar = hud;
   
    if (self.course) {
        self.url = [NSString stringWithFormat:@"%@/%@%@",[BTNetworkManager sharedMg].bathURL,kCourseDeload,self.course.courseUrl];
        if ([self.course.courseUrl rangeOfString:@"http:"].length) {
            self.url = self.course.courseUrl;
        }
        
    }else{
        self.url = @"";
    }
   
    [CKHttpCommunicate createDownloadFileWithURLString:self.url downloadFileProgress:^(NSProgress *progress) {
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            hud.progress = progress.fractionCompleted;
            hud.detailsLabelText = [NSString stringWithFormat:@"已下载%.f%%",progress.fractionCompleted *100];
        });
       
//        WSJLog(@"---%f,%f",progress,progress.completedUnitCount);
        
    } setupFilePath:^NSURL *(NSURLResponse *response) {

       
        return [NSURL fileURLWithPath: [HELPDFfileCacheTool getDownloadPathWithPdfName:weakSelf.course.courseName isMp4:NO]];
        
    } downloadCompletionHandler:^(NSURL *filePath, NSError *error) {
        
        if (error) {
            alertMessage(error.localizedDescription);

        }else{
            NSString *fullPath = [filePath path];
            [weakSelf preparePdfWithFilePath:fullPath];
            
            [hud hide:YES];
        }
      

    }];
    
    


 
}

- (void)preparePdfWithFilePath:(NSString *)path{
   
    
    
     MFDocumentManager * documentManager = [[MFDocumentManager alloc]initWithFileUrl:[NSURL fileURLWithPath:path]];
    _readerViewController = [[ReaderViewController alloc]initWithDocumentManager:documentManager];
    
    
    
  

    //_readerViewController.lastPage =self.studiedSeqNum;
    //[_readerViewController setDelegate:self];
    
    //    [_readerViewController setRemoteNavigationItem:self.navigationItem];
    
    weakSelf_define;
    _readerViewController.dismissBlock = ^{
       // [weakSelf.navigationController popViewControllerAnimated:YES];
        [weakSelf backAction];
    };
  
    
    if ([documentManager numberOfPages]== self.studiedSeqNum) {
         _readerViewController.isFinished = YES;
    }else{
     _readerViewController.isFinished = NO;
    }
   
    
    [self.view addSubview:_readerViewController.view];
   
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_readerViewController viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [_readerViewController viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_readerViewController viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_readerViewController viewDidDisappear:animated];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [_readerViewController willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [_readerViewController willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
}


@end
